import { useState, useEffect, useReducer } from 'react'
import http from '@/utils/http'
export function useProducts(url) {
	const [products, setProducts] = useState([])
	useEffect(() => {
		;(async () => {
			try {
				const { data } = await http.get(url)
				setProducts(data)
			} catch (error) {}
		})()
	}, [])
	return products
}
export function useDetail(url) {
	const [detail, setDetail] = useState([])
	useEffect(() => {
		;(async () => {
			try {
				const { data } = await http.get(url)
				setDetail(data)
			} catch (error) {}
		})()
	}, [])
	return detail
}

export function useCounterReducer(defaultValue, max) {
	const [count, dispatch] = useReducer(reducer, defaultValue)
	function reducer(count, { type, payload }) {
		switch (type) {
			case 'PLUS':
				return count + 1 > max ? count : count + 1
			case 'MINUS':
				return count - 1 < 0 ? count : count - 1
			case 'INPUT':
				return payload > max ? max : payload
			default:
				break
		}
	}
	return [count, dispatch]
}

/**
 * Counter 1 => 0 delete
 *         0 => 1 Add
 *         1 => 2 Modify
 * => useReducer
 * 组装cartList数据:
 * 1. 添加新商品 => 添加detail
 * 2. 删除商品 => 是将cartList数据中的指定商品剔除(用id寻找)
 * 3. 修改商品数量 => 用id找到商品,然后给商品的数量赋值
 */
export function useCart(cartData) {
	const [cartList, dispatch] = useReducer(reducer, cartData)
	function reducer(cartList, { type, payload }) {
		switch (type) {
			case 'ADD':
				// payload 格式: detail
				payload.cid = new Date().getTime()
        console.log(payload)
				return [payload, ...cartList]
			case 'DELETE':
				// payload 格式: id
				return cartList.filter(item => item.id != payload)
			case 'MODIFY':
				/**
				 * payload 格式
				 * {
				 *    id: x,
				 *    count: y
				 * }
				 */
				return cartList.map(item => {
					if (item.id === payload.id) {
						item.count = payload.count
					}
					return item
				})
			default:
				return cartList
		}
	}
  return [ cartList, dispatch ]
}


export function usePriceTotal(cartList) {
  const [total, setTotal] = useState(0)
  useEffect(() => {
    const sum = cartList.reduce((prev, next) => {
      return prev += next.count * next.price
    }, 0)
    setTotal(sum)
  }, [cartList])
  return total
}
// export function usePriceTotal(cartList) {
//   return cartList.reduce((prev, next) => {
//     return prev += next.count * next.price
//   }, 0)
// }
